package com.smart4j.chapter.common.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

import org.apache.commons.lang3.StringUtils;


/**
 * 自定义 filter 全局编码格式 ， 解决 post 请求 乱码 。
 */
@WebFilter(urlPatterns={"/*"},
			initParams={@WebInitParam(name = "encoding", value = "UTF-8")})
public class EncodeFilter implements Filter {
	
	/**
	 * 默认的编码格式 
	 */
	private static final String DEFAULT_ENCODE="UTF-8";
	
	/**
	 * 自定义编码格式 
	 */
	private String ENCODE ;
	
    /**
     * Default constructor. 
     */
    public EncodeFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		if(StringUtils.isNotBlank(ENCODE)){
			request.setCharacterEncoding(ENCODE);
			response.setCharacterEncoding(ENCODE);
		}else{
			request.setCharacterEncoding(DEFAULT_ENCODE);
			response.setCharacterEncoding(DEFAULT_ENCODE);
		}
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	@Override
	public void init(FilterConfig config) throws ServletException {
		ENCODE = config.getInitParameter("encoding");
	}

}
